﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Klinkby.Scheduler;

namespace Nebular.ExpenseManagement.SchedulerTasks
{   
    /// <summary>
    /// Implements a scheduled task that call RunJobs on the batchcontroller periodically
    /// </summary>
    public class PingTask : IScheduledTask
    {
        readonly IInterval _interval;
        readonly IBatchController _batchController;

        public PingTask(TimeSpan period, IBatchController batchController)
        {
            if (period.Ticks < 1)
                throw new ArgumentOutOfRangeException("period");
            if (batchController == null)
                throw new ArgumentNullException("batchController");
            _interval = new PeriodicInterval(period);
            _batchController = batchController;
        }

        #region IScheduledTask Members

        public void Execute()
        {
            _batchController.RunJobs();
        }

        public IInterval Interval
        {
            get 
            { 
                return _interval;
            }
        }

        #endregion

        sealed class PeriodicInterval : IInterval
        {
            readonly long _periodTicks;
            public PeriodicInterval(TimeSpan period)
            {
                _periodTicks = period.Ticks;
            }
        
            #region IInterval Members

            public DateTime Next
            {
	            get 
                {
                    DateTime now = DateTime.Now;
                    return now + new TimeSpan(now.Ticks % _periodTicks);
                }
            }

            #endregion
        }
    }
}
